<template>
	<div class="hy-container">
		<HyTable
			:searchFields="searchFields"
			:searchConfig="searchConfig"
			:searchDefault="searchDefault"
			:tableConfig="tableConfig"
			:tableColumns="tableColumns"
			ref="hyTableRef"
			:buttonConfig="{
				span: 4,
				offset: 1,
			}"
			:type="tabs"
			:tabls="tabls"
			@handleClick="handleClick"
		>
			<template #tableHeader>
				<el-button type="primary" @click="openTable('table')" icon="Plus">{{ typeTest == '1' ? '新增开发项目' : '新增运维项目' }}</el-button>
			</template>
			<template #dateSlot="{ row, column }">
				<el-button type="primary" plain v-if="row.declareTime">{{ row.declareTime }}</el-button>
				<span v-else>--</span>
			</template>
			<template #statusSlot="{ row, column }">
				<el-tag :class="setColor(row.status)">{{ isStatus(row.status).isStatusString }}</el-tag>
			</template>
			<template #operation>
				<el-table-column fixed="right" label="操作" width="130">
					<template #default="scoped">
						<el-button text type="primary" icon="View" @click="showDetails(scoped.row)">查看</el-button>
						<el-dropdown @command="handleCommand" class="dropdown-class">
							<el-button class="el-dropdown-link" text type="primary">
								更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
							</el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item
										command="a"
										v-if="scoped.row?.status == '1' || scoped.row?.status == '3'"
										style="color: var(--el-color-primary)"
										@click="showDetails(scoped.row)"
										:icon="Document"
										>申报</el-dropdown-item
									>
									<el-dropdown-item
										command="c"
										v-if="scoped.row?.status == '1' || scoped.row?.status == '3'"
										@click="getAppCode(scoped.row, 'edit')"
										style="color: #52c41a"
										:icon="Edit"
										>编辑</el-dropdown-item
									>
									<el-dropdown-item
										command="d"
										v-if="scoped.row?.status == '1' || scoped.row?.status == '3'"
										@click="getAppCode(scoped.row)"
										style="color: #f74e56"
										:icon="Delete"
										>删除</el-dropdown-item
									>
									<!--status为2表示申报中数据，且canCancel为true才能撤销-->
									<el-dropdown-item
										command="e"
										v-if="scoped.row?.status == '2'"
										@click="getAppCode(scoped.row, 'cancel')"
										:style="{ color: scoped.row?.canCancel == true ? '#f5222d' : '#C8C9CC' }"
										:disabled="!scoped.row?.canCancel"
										:icon="Reading"
										>撤销</el-dropdown-item
									>
									<el-dropdown-item
										command="h"
										v-if="scoped.row?.status == '2'"
										style="color: #a593e0"
										:icon="Reading"
										@click="openTable('form', scoped.row)"
										>修改申请</el-dropdown-item
									>
									<el-dropdown-item
										command="g"
										v-if="scoped.row?.status == '6'"
										style="color: #a593e0"
										:icon="Reading"
										@click="getAppCode(scoped.row, 'edit')"
										>修改</el-dropdown-item
									>
									<el-dropdown-item
										command="f"
										v-if="['2', '4', '5', '6'].indexOf(scoped.row.status) != -1"
										style="color: #13c2c2"
										:icon="Reading"
										@click.stop="historyTable(scoped.row)"
										>历史版本</el-dropdown-item
									>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</template>
				</el-table-column>
			</template>
		</HyTable>
		<!-- <el-button @click="openTable('table')">打开组件弹窗</el-button> -->
		<Dialog :dialogTitle="dialogTitle" :dialogTableVisible="dialogTableVisibleF" @closeDialog="closeDialog" :updateData="updateData"></Dialog>
		<!-- 历史详情 -->
		<ChooseRecords :visible="visibles" :businessType="'2'" :businessKey="declareId" @close="visibles = false" />
		<chooseApp
			:title="dialogTitle"
			:type="tableType"
			:searchFields="searchFieldsObjCom"
			:searchFieldsForm="searchFieldsForm"
			:searchDefault="searchDefault"
			:searchDefaultForm="searchDefaultForm"
			:tableColumns="appTableColumnsCom"
			:visible="openVisible"
			:updateData="updateData"
			@close="closeTable"
		></chooseApp>
		<Start ref="startRef" :boxConfig="{ title: '确认提交修改？', width: '40%' }" @submitPass="submitPass"></Start>
	</div>
</template>
<script lang="ts" setup>
import { ArrowDown, Document, Edit, Delete, Reading } from '@element-plus/icons-vue';
import HyTable from '/@/components/HyTable/index.vue';
import Dialog from '../dialog/index.vue';
import chooseApp from '../chooseApp/index.vue';
import {
	declarePage,
	declareDelete,
	declareCancel,
	declareCancelByNew,
	declareSubmit,
	dataModifySubmitApplication,
} from '/@/api/digitalList/digitalLization';
import Start from '@cqdcg/admin/views/flow/form/tools/startFlow';
import { cancel } from '@cqdcg/admin/views/flow/task/cancel';
import { getByIdAppDeclare } from '/@/api/decManagement/detail';
import { getDicts } from '/@/api/admin/dict';
import ChooseRecords from '/@/views/threeList/components/ChooseRecords/index.vue';
import type { TabsPaneContext } from 'element-plus';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useDict } from '/@/hooks/dict';
import mittBus from '/@/utils/mitt';
const hyTableRef = ref();
const tabs = ref('tabs');
const tabls = computed(() => {
	return {
		type: 'card',
		tablesList: [
			{
				lable: '开发项目',
				value: 1,
			},
			{
				lable: '运维项目',
				value: 2,
			},
		],
	};
});
//动作完后调用接口
const requestList = () => {
	hyTableRef.value.handleRest();
};
const typeTest = ref('1');
const searchDefault = computed(() => {
	return {
		type: typeTest.value,
	};
});
const deleteAppCode = ref(''); //
const deleteId = ref(''); //删除的id
const instanceId = ref(''); //撤销的id
const tableColumns = computed(() => {
	return [
		{ prop: 'appCode', label: '数字化应用编号', width: 300 },
		{ prop: 'appName', label: '数字化应用名称', width: 300 },
		{ prop: 'domain', label: '所属领域', width: 200 },
		{ prop: 'responsibleDept', label: '责任部门', width: 200 },
		{ prop: 'leadDept', label: '应用牵头部门', width: 200 },
		{ prop: 'declareTime', label: '申报时间', width: 300 },
		{ prop: 'status', label: '状态', slot: 'statusSlot', fixed: 'right' },
	];
});
const tableConfig = computed(() => {
	return {
		request: declarePage,
	};
});
const searchConfig = computed(() => {
	return {
		labelWidth: '120px',
		span: 6,
		offset: 0,
		type: 'search',
		title: '数字化应用申报',
		show: true,
	};
});
const searchFields = computed(() => {
	return {
		name: {
			type: 'input',
			label: '关键字',
			span: 7,
		},
		status: {
			type: 'select',
			label: '状态',
			span: 7,
			options: [
				{
					label: '待申报',
					value: '1',
				},
				{
					label: '申报中',
					value: '2',
				},
				{
					label: '已通过',
					value: '4',
				},
				{
					label: '未通过',
					value: '3',
				},
				{
					label: '修改审核中',
					value: '5',
				},
				{
					label: '修改中',
					value: '6',
				},
			],
		},
		timeArr: {
			type: 'date',
			span: 7,
			picker: 'datetimerange',
			label: '开始日期',
		},
	};
});
const router = useRouter();
//查看跳转
const showDetails = (row: any) => {
	let canCancel: any = null; //判断是否能够撤销传递给详情页
	if (row.status == 2 && row.canCancel == false) {
		canCancel = false;
	} else {
		canCancel = true;
	}
	router.push({
		path: '../detail/demandDeclaration',
		query: {
			title: searchConfig.value.title,
			status: row.status,
			canCancel: canCancel,
			id: row.declareId,
			appCode: row.appCode,
			instanceId: row.processInstanceId,
			processInstanceId: row.processInstanceId,
			pageTap: 'numDec',
		},
	});
};
const updateData = ref({});
const showUpdate = (data?: any) => {
	updateData.value = data;
};
//接收tab值调用接口
const handleClick = (tab: TabsPaneContext) => {
	switch (tab) {
		case '1':
			typeTest.value = '2';
			dialogTitle.value = '请选择方案中的运维项目';
			setTimeout(() => {
				requestList();
			}, 500);

			break;

		default:
			typeTest.value = '1';
			dialogTitle.value = '请选择方案中的开发项目';
			setTimeout(() => {
				requestList();
			}, 500);
			break;
	}
};
//读取状态
const isStatus = (str?: string) => {
	const obj = ref({
		isStatusString: '',
		statusButton: '',
	});
	switch (str) {
		case '2':
			obj.value.isStatusString = '申报中';
			obj.value.statusButton = 'primary';
			break;
		case '3':
			obj.value.isStatusString = '未通过';
			obj.value.statusButton = 'info';
			break;
		case '4':
			obj.value.isStatusString = '已通过';
			obj.value.statusButton = 'success';
			break;
		case '5':
			obj.value.isStatusString = '修改审核中';
			obj.value.statusButton = 'warning';
			break;
		case '6':
			obj.value.isStatusString = '修改中';
			obj.value.statusButton = 'danger';
			break;
		default:
			obj.value.isStatusString = '待申报';
			obj.value.statusButton = '';
			break;
	}
	return obj.value;
};
//弹窗相关数据
const dialogTableVisibleF = ref(false);
const dialogTitle = ref('请选择方案中的开发项目');
const timer = ref();
const closeDialog = (data?: Object) => {
	if (data) {
		if (data.is == true) {
			timer.value = setTimeout(() => {
				requestList();
			}, 500);
		} else {
			router.push({
				path: '../addDigitalLization/index',
				query: {
					chooseType: data.type,
					appCode: data.threeListCode,
					threeListName: data.threeListName,
					belongDomain: data.belongDomain,
					belongDomainName: data.belongDomainName,
					// liabilityDepartment: data.liabilityDepartment, //责任部门
					liabilityDepartment: data.responsibleDeptName, //责任部门新字段
					teamLeaderUnitName: data.teamLeaderUnitName, //应用牵头部门
					setAppCode: 'setAppCode',
				},
			});
		}
	} else {
		dialogTableVisibleF.value = false;
	}
	dialogTableVisibleF.value = false;
};
//接收下拉菜单传递的参数区别打开弹窗
const clickDropdown = (str?: string) => {
	if (str == 'history') {
		dialogTitle.value = '历史数据';
	} else {
		if (typeTest.value == '2') {
			dialogTitle.value = '请选择方案中的运维项目';
			dialogTableVisibleF.value = true;
		} else {
			dialogTitle.value = '请选择方案中的开发项目';
			dialogTableVisibleF.value = true;
		}
	}
};
//操作项逻辑处理
const handleCommand = (command: string | number | object) => {
	switch (command) {
		case 'a': //申报
			break;
		case 'd': //删除
			proxyMessage.value = '是否确定删除？';
			openElMessageBox();
			break;
		case 'e': //撤销
			// proxyMessage.value = '是否确定撤销？';
			// openElMessageBox();
			break;
		case 'f': //历史版本
			break;
		case 'h': //修改申请
			dialogTitle.value = '申请修改';
			// dialogTableVisibleF.value = !dialogTableVisibleF.value;
			break;
		default:
			break;
	}
};
const lizationData = ref({});
const getAppCode = async (row?: any, str?: string) => {
	deleteId.value = row.declareId;
	instanceId.value = row.processInstanceId;
	deleteAppCode.value = row.appCode;
	if (str == 'edit') {
		router.push({
			path: '../addDigitalLization/index',
			query: {
				declareId: row.declareId,
				editPage: 'editPage', //editPage标记为编辑
			},
		});
	}
	//申报不在直接请求，跳转详情
	if (str == 'tion') {
		await getByIdAppDeclare(row.declareId).then((res) => {
			lizationData.value = {
				...res.data,
			};
		});
	}
	//撤销
	if (str == 'cancel') {
		const obj = {
			processInstanceId: row.processInstanceId,
		};
		await cancel(obj)
			.then((res) => {
				console.log('撤回接口成功回调');
				requestList();
			})
			.catch((err) => {
				console.log('取消弹框和失败回调');
			});
	}
};
//消息删除提示
const proxyMessage = ref('');
const openElMessageBox = () => {
	ElMessageBox.confirm(
		proxyMessage.value, //提示内容
		'操作确认',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			// center: true,
		}
	)
		.then(() => {
			const loading = ElLoading.service({
				lock: true,
				text: '提交中...',
			});
			switch (proxyMessage.value) {
				case '是否确定删除？':
					declareDelete(deleteId.value)
						.then((res) => {
							ElMessage({
								type: res.code == 0 ? 'success' : 'error',
								message: res.code == 0 ? '操作成功' : '操作失败',
							});
						})
						.finally(() => {
							loading.close();
							setTimeout(() => {
								requestList();
							}, 300);
						});

					break;
				case '是否确定撤销？':
					// const cancelData = {
					// 	processInstanceId: instanceId.value,
					// 	processInstanceIdList: [instanceId.value],
					// 	paramMap: { operation: 'cancel' },
					// };
					// declareCancelByNew(cancelData) //新流程撤销
					// 	// declareCancel(instanceId.value)//原流程撤销
					// 	.then((res) => {
					// 		ElMessage({
					// 			type: res.code == 0 ? 'success' : 'error',
					// 			message: res.code == 0 ? '操作成功' : '操作失败',
					// 		});
					// 	})
					// 	.finally(() => {
					// 		loading.close();
					// 		setTimeout(() => {
					// 			requestList();
					// 		}, 300);
					// 	});
					break;
				case '是否确定提交？':
					declareSubmit(lizationData.value).then((res) => {
						ElMessage({
							type: 'success',
							message: '申报成功',
						});
						setTimeout(() => {
							requestList();
						}, 500);
					});
					// requestList();
					break;
				default:
					ElMessage({
						type: 'success',
						message: '操作成功',
					});
					setTimeout(() => {
						requestList();
					}, 300);
					break;
			}
		})
		.catch(() => {});
};
//历史详情
const visibles = ref(false);
const openVisible = ref(false);
const declareId = ref('');
const historyTable = (row: any) => {
	visibles.value = true;
	nextTick(() => {
		declareId.value = row.declareId;
	});
};
const openTable = (text?: any, data?: any) => {
	if (text == 'form') {
		dialogTitle.value = '申请修改';
	} else {
		if (typeTest.value == '2') {
			dialogTitle.value = '请选择方案中的运维项目';
		} else {
			dialogTitle.value = '请选择方案中的开发项目';
		}
	}
	tableType.value = text;
	updateData.value = data;
	openVisible.value = true;
};
//submitPass 为成功后的回调函数
const startRef = ref();
const submitPass = () => {
	timer.value = setTimeout(() => {
		requestList();
	}, 300);
};
const closeTable = (data?: any) => {
	if (data) {
		if (data.is == true) {
			startRef.value.handle({
				flowName: data.flowName,
				businessKey: data.businessKey,
			});
		} else {
			router.push({
				path: '../addDigitalLization/index',
				query: {
					chooseType: data.type,
					appCode: data.threeListCode,
					threeListName: data.threeListName,
					belongDomain: data.belongDomain,
					belongDomainName: data.belongDomainName,
					// liabilityDepartment: data.liabilityDepartment, //责任部门
					liabilityDepartment: data.responsibleDeptName, //责任部门新字段
					teamLeaderUnitName: data.teamLeaderUnitName, //应用牵头部门
					setAppCode: 'setAppCode',
				},
			});
		}
	} else {
		openVisible.value = false;
	}
	openVisible.value = false;
};
//设置颜色
const setColor = (type: string) => {
	switch (type) {
		case '1':
			return 'start-tag'; //待申报
		case '2':
			return 'wait-tag'; //申报中
		case '5':
		// return 'wait-tag'; //修改审核中
		case '3':
			return 'refuse-tag'; //未通过
		case '4': //已通过
			return 'agree-tag';
		default: //修改中
			return 'edit-tag';
	}
};
const tableType = ref('');
const appTableColumns = ref([
	{ prop: 'threeListName', slot: 'singleSlot', width: 50, fixed: 'left' },
	{ prop: 'threeListName', slot: 'indexSlot' },
	{ prop: 'threeListName', label: '数字化应用名称' },
	{ prop: 'threeListCode', label: '数字化应用编码' },
	{ prop: 'declarationTime', label: '填报时间' },
]);
const appTableColumnsCom = computed(() => {
	return appTableColumns.value;
});
const searchFieldsObj = ref({
	key: {
		label: '应用名称',
		type: 'input',
	},
});
const searchFieldsObjCom = computed(() => {
	return searchFieldsObj.value;
});
const searchFieldsForm = computed(() => {
	return {
		applyReason: {
			type: 'textarea',
			label: '修改意见',
			placeholder: '请输入修改意见',
			required: true,
		},
	};
});
const searchDefaultForm = ref({
	applyReason: '',
});
onUnmounted(() => {
	// 清除定时器
	clearTimeout(timer.value);
	timer.value = null;
});
</script>
<style scoped lang="scss">
.dropdown-class {
	margin-left: 10px;
}
</style>
